package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	// Step 1: 从配置文件加载
	config, err := loadConfig("config.yaml")
	if err != nil {
		panic(fmt.Sprintf("failed to read config file: %v", err))
	}

	zabbixURL := config.Zabbix.URL
	username := config.Zabbix.Username
	password := config.Zabbix.Password

	// Step 2: 获取认证 Token
	loginReq := Request{
		Jsonrpc: zabbixAPIVersion,
		Method:  "user.login",
		Params: map[string]interface{}{
			"username": username,
			"password": password,
		},
		ID: 1,
	}

	loginReqBody, _ := json.Marshal(loginReq)
	resp, err := http.Post(zabbixURL, contentType, bytes.NewBuffer(loginReqBody))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	var loginResp Response
	json.NewDecoder(resp.Body).Decode(&loginResp)
	if loginResp.Error != nil {
		panic(fmt.Sprintf("failed to login: %+v", loginResp.Error))
	}
	authToken := loginResp.Result.(string)

	// 创建 Prometheus exporter
	exporter := NewZabbixExporter(config.Zabbix.URL, authToken)

	// 设置 HTTP handler
	prometheus.MustRegister(exporter)
	http.Handle("/metrics", promhttp.Handler())

	// 启动 HTTP 服务器
	port := ":8080"
	fmt.Printf("Starting server on %s\n", port)
	go func() {
		log.Fatal(http.ListenAndServe(port, nil))
	}()

	// 使用 time.Ticker 每 5 秒从 Zabbix 获取数据并更新指标
	ticker := time.NewTicker(5 * time.Second)
	for range ticker.C {
		fetchAndUpdateMetrics(exporter)
	}
}
